package com.weblog.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.weblog.mapper.user.BaseUserMapper;
import com.weblog.model.user.User;
import com.weblog.utils.ObjectUtils;

public class CuestRealm extends AuthorizingRealm {

	@Autowired
	private BaseUserMapper baseUserMapper;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String username = (String) principalCollection.getPrimaryPrincipal();
		// 权限查询
		List<String> permissions = baseUserMapper.permissionList(username);
		// 身份查询
		List<String> roles = baseUserMapper.rolesList(username);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addStringPermissions(permissions);
		authorizationInfo.addRoles(roles);
		return authorizationInfo;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// 获取基于用户名和密码的令牌
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		// 根据用户名查找数据，查找用户
		if (!ObjectUtils.ObjectIsNotNull(token.getUsername())) {
			throw new UnknownAccountException();
		}
		// 根据用户名查找数据库，获取加密后的密码 和 盐
		User user = baseUserMapper.getUserByUserName(token.getUsername());
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(token.getUsername(),
				user.getUserPwd(), getName());
		authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getUserSalt())); // 加盐
		return authenticationInfo;
	}

}
